﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfByToolKit.CustomControl
{
    public class PasswordHelper
    {
        // 附加属性   propa

        public static string GetMyPassword(DependencyObject obj)
        {
            return (string)obj.GetValue(MyPasswordProperty);
        }

        public static void SetMyPassword(DependencyObject obj, string value)
        {
            obj.SetValue(MyPasswordProperty, value);
        }

        // Using a DependencyProperty as the backing store for MyPassword.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty MyPasswordProperty =
            DependencyProperty.RegisterAttached("MyPassword", typeof(string), typeof(PasswordHelper));



        //添加 附加属性   将控件值绑定到上面附加属性    从而 控件值绑定到vm值



        public static bool GetIsEnableBinding(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsEnableBindingProperty);
        }

        public static void SetIsEnableBinding(DependencyObject obj, bool value)
        {
            obj.SetValue(IsEnableBindingProperty, value);
        }

        // Using a DependencyProperty as the backing store for IsEnableBinding.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsEnableBindingProperty =
            DependencyProperty.RegisterAttached("IsEnableBinding", typeof(bool), typeof(PasswordHelper), new PropertyMetadata(false,OnPasswordPropertyChanged));

        private static void OnPasswordPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var c = d as PasswordBox;
            if(c is null)
            {
                return;
            }

            if ((bool)e.OldValue)
            {
                c.PasswordChanged -= OnPwdChange;
            }
            if ((bool)e.NewValue)
            {
                c.PasswordChanged += OnPwdChange;
            }
        }

        private static void OnPwdChange(object sender, RoutedEventArgs e)
        {
            var pwd = sender as PasswordBox;
            if (pwd is null)
                return;
            //将控件值 赋值给  附加属性
            SetMyPassword(pwd, "Password");
        }
    }
}
